package cn.bitkit.tools.net;

import cn.bitkit.tools.common.IOUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author changbo
 */
@Slf4j
public class SocketUtil {
	
	public static final int DEFAULT_TIMEOUT = 10000;
	public static final int DEFAULT_LINGER = 1;
	public static final int BUFF_LENGTH = 4096;
	

	public static String request(String ip, int port, String message) throws Exception{
		return request(ip, port, message, DEFAULT_TIMEOUT);
	}

	@SneakyThrows
	public static String request(String ip, int port, String message, int timeout) throws Exception{
		@Cleanup
		Socket socket = new Socket(ip, port);
		socket.setSoTimeout(timeout);
		socket.setTcpNoDelay(false);
		socket.setSoLinger(true, DEFAULT_LINGER);
		@Cleanup
		DataInputStream is = new DataInputStream(socket.getInputStream());
		@Cleanup
		DataOutputStream os = new DataOutputStream(socket.getOutputStream());
		os.writeUTF(message);
		os.flush();
		return is.readUTF();
	}
	
	public static byte[] request(String ip, int port, byte[] message) throws Exception{
		return request(ip, port, message, DEFAULT_TIMEOUT);
	}

	@SneakyThrows
	public static byte[] request(String ip, int port, byte[] message, int timeout) throws Exception{
		@Cleanup
		Socket socket = new Socket(ip, port);
		socket.setSoTimeout(timeout);
		socket.setTcpNoDelay(false);
		socket.setSoLinger(true, DEFAULT_LINGER);
		@Cleanup
		OutputStream os = socket.getOutputStream();
		@Cleanup
		InputStream is = socket.getInputStream();
		os.write(message);
		os.flush();
		return IOUtil.readBytes(is);
	}

}
